#define _CRT_SECURE_NO_WARNINGS 1
#include<vector>
#include <queue>
using namespace std;
using pii = pair<int, int>;
int c[] = { 0,0,1,-1 };
int d[] = { 1,-1,0,0 };
int n = 0, m = 0;
class Solution {
public:
    void bfs(vector<vector<int>>& sta, vector<vector<char>>& grid, int x, int y)
    {
        queue<pii> q;
        q.push({ x,y });
        while (!q.empty())
        {
            int a = q.front().first;
            int b = q.front().second;
            q.pop();
            for (int i = 0;i < 4;i++)
            {
                int j = a + c[i], k = b + d[i];
                if (j >= 0 && j < m && k >= 0 && k < n && grid[j][k] == '1' && sta[j][k] != 1)
                {
                    q.push({ j,k });
                    sta[j][k] = 1;
                }
            }
        }
    }
    int numIslands(vector<vector<char>>& grid)
    {
        m = grid.size();
        n = grid[0].size();
        vector<vector<int>> sta(m, vector<int>(n, 0));
        int count = 0;
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < n;j++)
            {
                //cout<<"["<<i<<","<<j<<"]:"<<grid[i][j]<<","<<sta[i][j]<<endl;
                if (grid[i][j] == '1' && sta[i][j] == 0)
                {
                    //cout<<i<<" "<<j<<endl;
                    count++;
                    bfs(sta, grid, i, j);
                    // for(auto a:sta)
                    // {
                    //     for(auto b:a) cout<<b<<" ";
                    //     cout<<endl;
                    // }
                }
            }
        }
        return count;
    }
};